﻿using System;
using com.yoozoo.gta.Extension.UGUI.ScreenOrientationEx;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.Gta.Common;

namespace com.yoozoo.gta.Tools.UI
{
    [ExecuteAlways]
    public class MarginScaler : MonoBehaviour
    {
        public bool left = true;
        public bool right = true;
        public bool top = false;
        public bool bottom = false;

        //[Tooltip("在以上设计尺寸最大宽度下，比标准尺寸多出的宽度值。比如标准尺寸1334下是边距是30，而1650尺寸下是80，则差异为50")]
        public int marginMinDelta = 22;
        public int marginMaxDelta = 96;
        /// <summary>
        /// 新增第2套 数值 用于right 和bottom
        /// </summary>
        public int secondMarginMinDelta = 22;
        public int secondMarginMaxDelta = 96;

        private bool isMarginInited; 

        //[Tooltip("设计尺寸的最大宽度，默认1650 * 750非必要不用改")]
        Vector2 uiMaxResolution = new Vector2(1650, 750);
        private Vector2 m_originMin;
        private Vector2 m_originMax;
        [NonSerialized]
        public bool forceRefreshInEditor = false;

        void Start()
        {
            //防止在MarginScalerAdapter.ApplyConfig方法执行后重复初始化

            RefreshMargin();
        }
        
#if UNITY_EDITOR
        
        void OnValidate()
        {
            var childMargins = GetComponentsInChildren<MarginScaler>(true);
            if (childMargins != null)
            {
                foreach (var margin in childMargins)
                {
                    if (!margin.Equals(this) && margin.enabled)
                    {
                        UnityEngine.Debug.LogError($" {name} 节点的子节点 {margin.name} 有MarginScaler组件", this);
                    }
                }
            }

            // OnValidate在加载Prefab资源的时候会执行，如果执行RefreshMargin，会导致Start的时候重复计算margin
            
            // RefreshMargin();
        }
        
#endif

        public void RefreshMargin()
        {
            //非运行模式不修改rectTransform
            if (Application.isPlaying || forceRefreshInEditor)
            {
                var rectTrans = (RectTransform)this.transform;
                rectTrans.offsetMin = Vector2.zero;
                rectTrans.offsetMax = Vector2.zero;   //挂载MarginScaler组件不允许调整RectTransform，如有需要，在父节点处理
                
                this.m_originMin = rectTrans.offsetMin;
                this.m_originMax = rectTrans.offsetMax;
                CheckAndFixMargin();
            }
        }

        private void CheckAndFixMargin()
        {
            Vector2Int screenSize = ScreenOrientManager.GetInstance().GameViewSize();
   #if !UNITY_EDITOR
            double currAspect = Math.Round((float) screenSize.x / screenSize.y, 2); 
            double realAspect = Math.Round(DeviceInfo.GetRealScreenAspect(), 2);
            if (!currAspect.Equals(realAspect))
            {
                //当前的屏幕比例和屏幕的物理比例不一致 则表示当前不是全屏状态(可能设置了安全区域不显示)
                //非全屏状态 不检测异形屏
                Debug.LogWarning($"当前应用没有全屏显示 请检查系统设置 curr:{currAspect}  real:{realAspect}");
                return;
            }
   #endif
            GameObject rootCanvasGo = null; 
            CanvasScaler canvasscaler = null;
            if (Application.isPlaying)
            {
                 rootCanvasGo = ResidentHandler.Inst.RootCanvas;
                 canvasscaler = rootCanvasGo.GetComponent<CanvasScaler>();
            }
            else
            {
                canvasscaler = GetComponentInParent<CanvasScaler>();
                if (canvasscaler)
                {
                    rootCanvasGo = canvasscaler.gameObject;
                }
               
            }
            if (rootCanvasGo != null)
            {
                var rectTrans = (RectTransform)this.transform;
                if (rectTrans.anchorMin == new Vector2(0, 0) && rectTrans.anchorMax == new Vector2(1, 1))
                {
                    float resolutionX = canvasscaler.referenceResolution.x;
                    float resolutionY = canvasscaler.referenceResolution.y;
                
                    var scaleX = screenSize.x / resolutionX;
                    var scaleY = screenSize.y / resolutionY;
                    var scaleFactor = math.min(scaleX, scaleY);
                    var scaleWidth = screenSize.x / scaleFactor;
                    var scaleHeight = screenSize.y / scaleFactor;

                    var maxWidth = screenSize.x > screenSize.y ? uiMaxResolution.x : uiMaxResolution.y;
                    var maxHeight = screenSize.x > screenSize.y ? uiMaxResolution.y : uiMaxResolution.x;
                    
                    //超过的按照最大值计算
                    if (scaleWidth > maxWidth) scaleWidth = maxWidth;
                    if (scaleHeight > maxHeight) scaleHeight = maxHeight;
 
                        
                    var originalLeft = this.m_originMin.x;
                    var originalBottom = this.m_originMin.y;
                    var originalRight = this.m_originMax.x;
                    var originalTop = this.m_originMax.y;
                    float marginLeft, marginRight,  marginTop, marginBottom;
                    
                    if (scaleWidth > resolutionX)
                    {
                        marginLeft = (marginMaxDelta * (scaleWidth - resolutionX) + marginMinDelta * (maxWidth - scaleWidth))
                            / (maxWidth - resolutionX) + originalLeft;
                        marginRight = (secondMarginMaxDelta * (scaleWidth - resolutionX) + secondMarginMinDelta * (maxWidth - scaleWidth))
                            / (maxWidth - resolutionX) + originalLeft;
                    }
                    else
                    {
                        marginLeft = marginMinDelta + originalLeft;
                        marginRight = secondMarginMinDelta + originalRight;
                    }

                    if (scaleHeight > resolutionY)
                    {
                        marginTop = (marginMaxDelta * (scaleHeight - resolutionY) + marginMinDelta * (maxHeight - scaleHeight))
                            / (maxHeight - resolutionY) + originalLeft;
                        marginBottom = (secondMarginMaxDelta * (scaleHeight - resolutionY) + secondMarginMinDelta * (maxHeight - scaleHeight))
                            / (maxHeight - resolutionY) + originalLeft;
                    }
                    else
                    {
                        marginTop = marginMinDelta + originalBottom;
                        marginBottom = secondMarginMinDelta + originalBottom;
                    }

                    var finalLeft = left ? marginLeft : originalLeft;
                    var finalRight = right ? -marginRight : originalRight;
                    var finalTop = top ? -marginTop : originalTop;
                    var finalBottom = bottom ? marginBottom : originalBottom;
                    rectTrans.offsetMin = new Vector2(finalLeft, finalBottom);
                    rectTrans.offsetMax = new Vector2(finalRight, finalTop);
                }

            }
        }
    }
}